<?php


namespace app\admin\service\base;


use app\admin\model\base\Subject;
use app\admin\model\base\Subject as Question;
use app\admin\model\base\SubjectAnswer;
use app\admin\validates\PractiseValidate;
use app\admin\validates\SubjectValidate;
use app\BaseService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class SubjectService  extends BaseService
{
    /**
     * 列表
     * @param array $params
     * @return Json
     */
    public function index(array $params): Json
    {
        $where[] = ['is_del','=',0];
        if(isset($params['question_id'])){
            $where[] = ['question_id','=',$params['question_id']];
        }
        if(isset($params['attr']) && $params['attr']){
            $where[] = ['attr','like','%'.$params['attr'].'%'];
        }
        //获取列表
        $data = Question::getList($where, $params['page'] ?? 1, $params['limit'] ?? 100, 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 导入题目
     * @param array $params
     * @return Json
     */
    public function import(array $params):Json
    {
        // 获取表单上传文件
        $file[] = request()->file('file');
        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])
                ->check(['file'=>$file[0] ?? '']);
            $savename =\think\facade\Filesystem::disk('public')->putFile('upload', $file[0]);
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load(public_path().$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                throw new \Exception('数据不能为空');
            }
            $arrTitle = foundExcelColumnName(50);
            $types = ['简答题'=>3,'单选题'=>1,'多选题'=>2];
            $degreeTypes = ['高'=>0,'中'=>1,'低'=>2];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            $dataArr = [];
            for ($j = 2; $j <= $highestRow; $j++) {
                $da = [];
                $name = '';
                $type = '';
                $content = [];
                $type = '';
                $type = '';
                $typeName = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                $type = $types[$typeName] ?? 0;
                $name = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                $analysis_desc = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()) ?? '';
                $degrees = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()) ?? '';
                $degree = $degreeTypes[$degrees] ?? '';
                $weighting = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()) ?? '';
                $attr = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()) ?? '';
                $analysis = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()) ?? '';
                if($type == 3){
//                    if($analysis_desc == ''){
//                        continue;
//                    }
                }
                if($degree == ''){
                    continue;
                }
                $content['list'] = [];
                if($type == 1 || $type == 2){
                    for ($i = 0;$i<= count($arrTitle);$i++){
                        if($i >= 7){
                            //读取选项
                            $v = trim($objPHPExcel->getActiveSheet()->getCell($arrTitle[$i] . $j)->getValue());
                            if($v == ''){
                                break;
                            }
                            $da[] = [
                                'title'=>$v,
                                'sort'=>$i-6,
                                'lable'=>$arrTitle[$i-7],
                                'is_answer'=>in_array($arrTitle[$i-7],explode(',',$analysis)) ? true : false,
                            ];
                        }
                    }
                    //组装处理数据
                    $content['list'] = $da;
                    //验证答案和选项
                    if(count($content['list']) < 4 || $analysis == ''){
                        continue;
                    }
                }
                if($type && $name && $degree != '' && $attr != '' && $weighting != ''){
                    $dataArr[] = [
                        'title'=>$name,
                        'degree'=>$degree,
                        'type'=>$type,
                        'create_user'=>0,
                        'analysis_desc'=>$analysis_desc,
                        'analysis'=>$analysis,
                        'attr'=>$attr,
                        'weighting'=>$weighting,
                        'content'=>json_encode($content),
                        'question_id'=>$params['id'],
                    ];
                }
            }
            $model = new Subject();
            $res = $model->saveAll($dataArr);
            if(!$res){
                throw new \Exception('导入数据库失败');
            }
            return jsonReturn(1, ['num'=>count($dataArr)]);
        } catch (\think\exception\ValidateException $e) {
            return jsonReturn(0, [],$e->getMessage());
        }
    }

    /**
     * 详情
     * @param array $params
     * @return Json
     */
    public function read(array $params): Json
    {
        //数据验证
        try {
            validate(SubjectValidate::class)->scene('details')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $where = ['id'=>$params['id']];
        $data = Question::where($where)->with(['question_cates'])->find();
        return jsonReturn(1, $data);
    }

    /**
     * 保存班级
     * @param array $params
     * @return Json
     */
    public function save(array $params): Json
    {
        //数据验证
        try {
            validate(SubjectValidate::class)->scene('add')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        Db::startTrans();
        try {
            //处理答案
            if($params['type'] == 1 || $params['type'] == 2){
                $analysis = [];
                $content = json_decode($params['content'],true);
                if(isset($content['list']) && !empty($content['list'])){
                    foreach ($content['list'] as $analysiss){
                        if($analysiss['is_answer'] == true){
                            $analysis[] = $analysiss['lable'];
                        }
                    }
                }

                $params['analysis'] = implode(',',$analysis);
            }
            $data = Question::create([
                'title'=>$params['title'],
                'degree'=>$params['degree'],
                'create_user'=>WS_ADMIN_ID,
                'type'=>$params['type'],
                'weighting'=>$params['weighting'] ?? 0,
                'question_id'=>$params['question_id'],
                'analysis'=>$params['analysis'] ?? '',
                'analysis_desc'=>$params['analysis_desc'],
                'content'=>$params['content'],
                'attr'=>$params['attr'] ?? '',
            ]);
            if(!$data){
                throw new \Exception('保存题目失败!');
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return jsonReturn(0, [],$exception->getMessage());
        }
        return jsonReturn(1, []);
    }

    /**
     * 编辑
     * @param array $params
     * @return Json
     */
    public function update(array $params): Json
    {
        //数据验证
        try {
            validate(SubjectValidate::class)->scene('edit')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //处理答案
        if($params['type'] == 1 || $params['type'] == 2){
            $analysis = [];
            $content = json_decode($params['content'],true);
            if(isset($content['list']) && !empty($content['list'])){
                foreach ($content['list'] as $analysiss){
                    if($analysiss['is_answer'] == true){
                        $analysis[] = $analysiss['lable'];
                    }
                }
            }

            $params['analysis'] = implode(',',$analysis);
        }
        $updateData = [
            'title'=>$params['title'],
            'degree'=>$params['degree'],
            'type'=>$params['type'],
            'question_id'=>$params['question_id'],
            'weighting'=>$params['weighting'] ?? 0,
            'analysis'=>$params['analysis'],
            'analysis_desc'=>$params['analysis_desc'],
            'content'=>$params['content'],
            'attr'=>$params['attr'] ?? '',
        ];
        $data = Question::where('id','=',$params['id'])->update($updateData);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 编辑班级
     * @param array $params
     * @return Json
     */
    public function delete(array $params): Json
    {
        //数据验证
        try {
            validate(SubjectValidate::class)->scene('del')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        $data = Question::where('id','=',$params['id'])->update(['is_del'=>1]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 题目启用和禁止
     * @param array $params
     * @return Json
     */
    public function do_status(array $params): Json
    {
        //数据验证
        try {
            validate(SubjectValidate::class)->scene('del')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        if($params['status'] == 1){
            $status = 1;
        }else{
            $status = 0;
        }
        $data = Question::where('id','=',$params['id'])->update(['status'=>$status]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

}